# -*- coding: utf-8 -*-
"""
简化配置管理模块
负责从config.json读取静态配置
"""

import ujson as json
import uos

# ============================================================================
# 全局变量
# ============================================================================

_config = None
_config_file = "/haas/config.json"

# ============================================================================
# 系统全局状态变量 - 避免循环引用
# ============================================================================

# 网络状态
g_network_ready = False
g_time_synced = False

# MQTT状态
g_mqtt_connected = False

# 系统状态
g_system_status = "starting"  # starting, running, error, shutdown

# ============================================================================
# 配置加载函数
# ============================================================================


def load_config():
    """加载配置文件"""
    global _config
    list_json = uos.listdir("/haas/")
    if ("config.json") in list_json:
        print("[CONFIG] Config file exists, load_config successfully.")
        pass
    else:
        uos.rename("/luadb/config.json","/haas/config.json")
        # flash_config()

    try:
        with open(_config_file, "r") as f:
            _config = json.load(f)

        return True

    except Exception as e:
        print("[CONFIG] Failed to load config: {}".format(e))
        _config = None
        return False


# ============================================================================
# 配置访问函数
# ============================================================================


def get_config(key_path=None, default_value=None):
    """获取配置值

    Args:
        key_path: 配置路径，如 'device.device_sn' 或 'intervals.data_collection'
        default_value: 默认值，当配置不存在时返回

    Returns:
        配置值或默认值
    """
    if _config is None:
        load_config()

    if not key_path:
        return _config

    keys = key_path.split(".")
    value = _config

    try:
        for key in keys:
            value = value[key]
        return value
    except (KeyError, TypeError):
        return default_value


def get_device_info():
    """获取设备信息"""
    return get_config("device") or {}


def get_device_sn():
    """获取设备序列号"""
    device_info = get_device_info()
    return device_info.get("device_sn", None)


def get_mqtt():
    """获取MQTT配置"""
    device_sn = get_device_sn()
    product_id = get_config("device.product_id", "1930147024035573760")
    mqtt_secret = get_config("device.mqtt_secret", "12345")

    mqtt_base = get_config("mqtt") or {}

    return {
        "enabled": True,
        "broker": mqtt_base.get("broker", "47.116.78.156"),
        "port": mqtt_base.get("port", 1883),
        "client_id": "{}&{}&{}".format(device_sn, product_id, mqtt_secret),
        "username": mqtt_base.get("username", "liuzong"),
        "password": mqtt_base.get("password", "liuzong888@iot"),
        "keepalive": mqtt_base.get("keepalive", 60),
        "qos": mqtt_base.get("qos", 1),
        "topics": {
            "data": "/{}/{}/properties/report".format(product_id, device_sn),
            "result": "/{}/{}/properties/reportResult".format(product_id, device_sn),
            "control": "/{}/{}/properties/write".format(product_id, device_sn),
            "status": "/{}/{}/properties/status".format(product_id, device_sn),
        },
    }


def get_intervals():
    """获取所有间隔配置（必须从config.json获取）"""
    intervals = get_config("intervals")
    if intervals is None:
        print("[CONFIG] Warning: intervals not found in config.json")
        return {}
    return intervals


def get_interval(task_name):
    """获取特定任务的间隔（必须从config.json获取）"""
    intervals = get_intervals()
    value = intervals.get(task_name)
    if value is None:
        print(
            "[CONFIG] Warning: interval '{}' not found in config.json".format(task_name)
        )
    return value


def get_network_recovery():
    """获取网络恢复配置"""
    network_config = get_config("network") or {}
    return network_config


def get_system():
    """获取系统配置"""
    return get_config("system") or {}


# ============================================================================
# 初始化函数
# ============================================================================


def init():
    """初始化配置模块"""
    return load_config()


def start():
    """启动配置模块"""
    return True


def set_config(key_path, value):
    """设置配置值并保存到文件

    Args:
        key_path: 配置路径，如 'device.device_sn' 或 'mqtt.broker'
        value: 要设置的值

    Returns:
        bool: 设置是否成功
    """
    global _config

    if _config is None:
        load_config()

    if _config is None:
        return False

    keys = key_path.split(".")
    current = _config

    try:
        # 导航到目标位置
        for key in keys[:-1]:
            if key not in current:
                current[key] = {}
            current = current[key]

        # 设置值
        current[keys[-1]] = value

        # 保存到文件
        return save_config()

    except Exception as e:
        print("[CONFIG] Failed to set config '{}': {}".format(key_path, e))
        return False


def save_config():
    """保存配置到文件"""
    global _config

    if _config is None:
        print("[CONFIG] Config is None, cannot save.")
        return False

    try:
        with open(_config_file, "w+") as f:
            # MicroPython的json.dump可能不支持indent参数
            json.dump(_config, f)
        return True
    except Exception as e:
        print("[CONFIG] Failed to save config: {}".format(e))
        return False


def get_supported_config_keys():
    """动态获取支持的配置键列表"""
    if _config is None:
        load_config()

    if _config is None:
        return []

    keys = []

    def _flatten_dict(d, prefix=""):
        """递归展开字典为点分隔的键名"""
        for key, value in d.items():
            if prefix:
                full_key = "{}.{}".format(prefix, key)
            else:
                full_key = key

            if isinstance(value, dict):
                _flatten_dict(value, full_key)
            else:
                keys.append(full_key)

    _flatten_dict(_config)
    return sorted(keys)


def flash_config():
    global _config
    config_json = None
    device_sn = get_device_sn()
    try:
        init_config_file = "/luadb/config.json"
        with open(init_config_file, "r") as f:
            config_json = json.load(f)
        if config_json:
            _config = config_json
            save_config()
        if device_sn:
            set_config("device.device_sn", device_sn)
        print("[CONFIG] flash_config success,config:{}".format(_config))
        return config_json
    except Exception as e:
        print("[CONFIG] flash_config error:", e)
    return config_json


def get_module_info():
    """获取模块信息"""
    return {
        "name": "Simple Configuration Manager",
        "version": "v1.0.0",
        "description": "Simplified static configuration management",
        "config_loaded": _config is not None,
    }


# 自动加载配置
load_config()
